import { useMemo, useState } from 'react';
import { buildBSTFromArray, findMode } from '@ds/tree';
import { Space, Input, Typography, Alert, Tag } from 'antd';

export default function BSTMode() {
  const [input, setInput] = useState('1,2,2,3');
  const values = useMemo(
    () =>
      input
        .split(/[\,\s]+/)
        .filter(Boolean)
        .map(Number)
        .filter((n) => Number.isFinite(n)),
    [input]
  );
  const root = useMemo(() => buildBSTFromArray(values), [values]);
  const modes = useMemo(() => findMode(root), [root]);

  return (
    <Space direction="vertical" size="middle" style={{ width: '100%' }}>
      <Typography.Title level={2}>LeetCode 501. 二叉搜索树中的众数</Typography.Title>
      <Alert
        message="题目说明"
        description={
          <Typography.Paragraph style={{ marginBottom: 0 }}>
            给定二叉搜索树的根节点，返回出现次数最多的值（可能不止一个）。 本页面直接调用算法模块
            `findMode`，实现基于中序遍历统计频次。
            <Typography.Link
              href="https://leetcode.cn/problems/find-mode-in-binary-search-tree/"
              target="_blank"
              style={{ marginLeft: 8 }}
            >
              题目链接
            </Typography.Link>
          </Typography.Paragraph>
        }
        type="info"
        showIcon
      />

      <Space>
        <Input
          allowClear
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="例如: 1,2,2,3"
          style={{ width: 360 }}
        />
      </Space>

      <Alert
        message={
          modes.length === 0 ? (
            '无众数（空树）'
          ) : (
            <span>
              众数：
              {modes.map((m) => (
                <Tag key={m} color="blue" style={{ marginLeft: 4 }}>
                  {m}
                </Tag>
              ))}
            </span>
          )
        }
        type={modes.length === 0 ? 'warning' : 'success'}
        showIcon
      />

      <Typography.Text type="secondary">
        注：数组按当前插入策略构建 BST（相等值进入右子树）。
      </Typography.Text>
    </Space>
  );
}
